<template>
  <div>
    <el-dialog title="采购入库单详情"  width="1200px" @open="open" class="icon-dialog" :visible.sync="show" :before-close="closeForm" append-to-body>
      <div>
        <el-button type="primary" size="small" icon="el-icon-check" @click="auditPurIn" :disabled="checked">审核</el-button>
      </div>
      <el-form ref="form" :model=" purinform " size="small" label-width="80px" :inline="true" class="header">
        <el-row>
          <el-col :span="10">
            <el-form-item label="单据编号:" class="no-wrap-label">{{ purinform.billNo }}</el-form-item>
          </el-col>
<!--          <el-col :span="10">-->
<!--            <el-form-item label="入库日期:" class="no-wrap-label">{{ purinform.auditTime }}</el-form-item>-->
<!--          </el-col>-->
          <el-col :span="10">
            <el-form-item label="入库时间:" class="no-wrap-label">
              <el-date-picker
                v-model="customAuditDateTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择入库日期时间"
                :disabled="checked"
                style="width: 220px;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="质检员:" class="no-wrap-label">{{ purinform.inspectUser }}</el-form-item>
          </el-col>
<!--          <el-col :span="10">-->
<!--            <el-form-item label="仓管员:" class="no-wrap-label">{{ receform.fmaterialnumber }}</el-form-item>-->
<!--          </el-col>-->
          <el-col :span="10">
            <el-form-item label="供应商:" class="no-wrap-label">{{ purinform.supplierName }}</el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="来料检验:" class="no-wrap-label">{{ purinform.inspectBillNo }}</el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="收料单号:" class="no-wrap-label">{{ purinform.receiveBillNo }}</el-form-item>
          </el-col>
        </el-row>

        <br />
      </el-form>
      <!-- 实收数量合计 -->
      <div style="text-align: right; margin: 10px 0; font-weight: bold; color: #409EFF; font-size: 14px;">
        实收数量合计：{{ totalRealQty }}
      </div>
      <el-table :data="purinList" height="calc(100vh - 300px)">
        <!--        <el-table-column label="No." width="60" align="right" type="index"></el-table-column>-->
        <el-table-column label="收料单号" width="120" prop="receiveBillNo"></el-table-column>
        <el-table-column label="物料编码" width="120" prop="materialNo"></el-table-column>
        <el-table-column label="物料名称" width="120" prop="materialName"></el-table-column>
        <el-table-column label="规格型号" width="120" prop="specification"></el-table-column>
        <el-table-column label="单位名称" width="120" prop="unitName"></el-table-column>
        <el-table-column label="应收数量" width="120" prop="mustQty"></el-table-column>
        <el-table-column label="实收数量" width="120" prop="realQty">
          <template slot-scope="scope">
            <el-input
                v-model="scope.row.realQty"
                size="mini"
                placeholder="请输入"
                @input="handleRealQtyInput(scope.row)"
            />
          </template>
        </el-table-column>

        <el-table-column v-if="purinform.isWeight" label="地磅称重数量" width="120" prop="weightQty"></el-table-column>
        <el-table-column label="入库仓库" width="120" prop="stockName">
          <template slot-scope="scope">
            <el-select v-model="scope.row.stockNo" @change="change(scope.row)">
              <el-option
                  v-for="item in scope.row.stockList"
                  :key="item.value"
                  :label="item.text"
                  placeholder="请选择仓库"

                  :value="item.value">
              </el-option>
            </el-select>
          </template>

        </el-table-column>

        <el-table-column label="仓位" width="120" prop="locationNo">
          <template slot-scope="scope" v-if="scope.row.isLocation">
            <el-input placeholder="请输入仓位" v-model="scope.row.locationNo" @blur="checkLocation(scope.row)" ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="单位编码" width="120" prop="unitNo"></el-table-column>
        <el-table-column label="批号" width="120" prop="flot">
          <template slot-scope="scope" >
            <el-input placeholder="请输入批号" v-model="scope.row.flot"  ></el-input>
          </template>
        </el-table-column>


      </el-table>


    </el-dialog>

  </div>
</template>
<script>
import { detail,auditPurIn  } from '@/api/app/purin'
import {checkStock,getLocation} from '@/api/app/warehouse'
import {auditInspect} from "@/api/app/inspect";
export default {
	name:'purIndetail',
	props: {
		show: {
			type: Boolean,
			default: true
		},
		size: {
			type: String,
			default: 'mini'
		},
		info: {
			type: Object,
		},
	},
	data() {
		return {
      purinform:{},
      purinList:[],
      checked:false,
      customAuditDateTime: '', // 新增字段用于存储自定义入库时间
		}
	},
	watch:{
		show(val){
			if(val){
			}
		}
	},
	methods: {
    checkStatus(){
      if (this.purinform.status === 'save'){
        this.checked = false;
      } else {
        this.checked = true;
      }
    },
    handleRealQtyInput(row) {

      let val = row.realQty.toString();
      // 只保留数字和最多两位小数
      val = val.replace(/[^\d.]/g, '')             // 去除非数字和点
          .replace(/^0+(\d)/, '$1')           // 去除多余前导零
          .replace(/^\./, '0.')               // 以点开头补零
          .replace(/\.{2,}/g, '.')            // 多个点合并为一个
          .replace('.', '#')                  // 临时替换第一个点
          .replace(/\./g, '')                 // 移除其他点
          .replace('#', '.')                  // 恢复第一个点
          .replace(/^(\d+)(\.\d{0,2}).*$/, '$1$2'); // 限制两位小数

      let num = parseFloat(val);
      let max = parseFloat(row.mustQty || 0);
      // 限制不能大于应收数量
      if (!isNaN(num) && num > max) {
        this.$message.warning('实收数量不能大于应收数量');
        val = max.toFixed(2); // 转为两位小数字符串
      }
      row.realQty = val;
    },

    //审核采购入库单
    auditPurIn(){
      let self = this;
      this.$confirm('是否确认审核', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '正在审核'
        });
        auditPurIn({billNo : this.purinform.billNo,dataList : this.purinList,customAuditDateTime : this.customAuditDateTime}).then(res =>{
          if (res.data){
            this.$message({
              type: 'success',
              message: '审核成功!'
            });
            this.$emit('refresh_list'); // ✅ 通知父组件刷新
            this.closeForm()
          }
        })
      })
    },
    //校验仓位
    checkLocation(row){
      if(!row.locationNo  || row.locationNo.trim() === ''){
        this.$message({
          message:'仓位为空',
          type:'warning'
        })
        return;
      }
      if (!row.locationList.includes(row.locationNo)){
        row.locationNo = ''
        this.$message({
          message:'仓位错误请重试',
          type:'warning'
        })
        return;
      }

    },
    //修改仓库后重新校验仓库有没有启用仓位
    change(item){
      for(let i =0;i < item.stockList.length;i++){
        if (item.stockList[i].value == item.stockNo){
          item.stockName = item.stockList[i].text
        }
      }
      this.checkStock(item.stockNo,item)
      //将仓位赋值为空
    },
    //检查当前仓库是否启用仓位
    checkStock(stockNo,item){
      checkStock({stockNo : stockNo}).then(res =>{
        item.isLocation = res.data
        //如果仓库启用仓位的话查询仓位信息
        if (item.isLocation){
          this.getLocation(stockNo,item)
        }
      })
    },
    //获取仓位信息
    getLocation(stockNo,item){
      console.log('获取仓位信息')
      getLocation({stockNo:stockNo}).then(res =>{
        item.locationList = res.data
      })
    },

    open(){
      detail(this.info).then(res => {

        if (res.status == 200) {
          this.purinform = res.data.data;
          this.purinList = res.data.dataList;
          this.checkStatus()

        } else {
          this.$message.error('获取详情失败2，请稍后再试');
        }
      }).catch(error => {

        this.$message.error('获取详情失败，请稍后再试');
      });
		},
		closeForm(){
			this.$emit('update:show', false)
		}
	},
computed: {
  totalRealQty() {
    return this.purinList.reduce((sum, row) => {
      let num = parseFloat(row.realQty)
      return sum + (isNaN(num) ? 0 : num)
    }, 0).toFixed(2)
  }
}

}
</script>
<style  lang="scss">
@import '@/assets/scss/common.scss';
</style>
